﻿using System;
using System.Collections.Generic;
using System.Text;
using wxLib.Lib;
using WxLib;

namespace wxLib.Pay
{
    /// <summary>
    /// 扫码支付
    /// </summary>
    public class NativePay
    {
        /// <summary>
        /// 扫码支付返回微信支付码
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public string GetPrePayUrl(string productId)
        {
            WxApiOptions wxPayConfig = new WxApiOptions();
            WxPayData data = new WxPayData();
            data.SetValue("appid", wxPayConfig.AppId);//公众帐号id
            data.SetValue("mch_id", wxPayConfig.MchId);//商户号
            data.SetValue("time_stamp", Senparc.Weixin.MP.TenPayLibV3.TenPayV3Util.GetTimestamp());//时间戳
            data.SetValue("nonce_str", Senparc.Weixin.MP.TenPayLibV3.TenPayV3Util.GetNoncestr());//随机字符串
            data.SetValue("product_id", productId);//商品ID
            data.SetValue("sign", data.MakeSign("MD5"));//签名
            string str = ToUrlParams(data.GetValues());//转换为URL串
            string url = "weixin://wxpay/bizpayurl?" + str;
            return url;
        }

        /**
        * 参数数组转换为url格式
        * @param map 参数名与参数值的映射表
        * @return URL字符串
        */
        private string ToUrlParams(SortedDictionary<string, object> map)
        {
            string buff = "";
            foreach (KeyValuePair<string, object> pair in map)
            {
                buff += pair.Key + "=" + pair.Value + "&";
            }
            buff = buff.Trim('&');
            return buff;
        }

    }
}
